import axios from 'axios'
import { Loading, Message } from 'element-ui'
import { isEmpty } from './util'
import router from '../router'
import { BASE_HTTP_URL } from './global'

const _token = sessionStorage.getItem('token')
const httpService = axios.create({
  //配置请求根路径
  baseURL: BASE_HTTP_URL,
  timeout: 300000
})

const err = error => {
  if (!isEmpty(loading)) {
    loading.close()
  }

  if (error.response) {
    let data = error.response.data
    const token = _token
    console.log('------异常响应------', token)
    console.log('------异常响应------', error.response.status)
    switch (error.response.status) {
      case 401:
        Message({
          message: isEmpty(data.message) ? '授权异常' : data.message,
          type: 'error'
        })
        break
      case 500:
        Message({
          message: isEmpty(data.message) ? '系统异常' : data.message,
          type: 'error'
        })
        break
      default:
        Message({
          message: data.message,
          type: 'warning'
        })
        break
    }
  }
  return Promise.reject(error)
}

// axios请求拦截
let loading
httpService.interceptors.request.use(
  config => {
    // console.log(config)
    if (isEmpty(config.bLoading) || config.bLoading) {
      loading = Loading.service({ fullscreen: true, text: 'Loading....', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0)' })
    }
    //为请求头对象，添加token 验证的Authorization 字段
    const token = sessionStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = 'Bearer ' + token
    }
    // 必须最后return config
    return config
  },
  error => {
    if (!isEmpty(loading)) {
      loading.close()
    }
    return Promise.reject(error)
  }
)

httpService.interceptors.response.use(res => {
  if (!isEmpty(loading)) {
    loading.close()
  }
  return res.data
}, err)

export default httpService
